package com.yupi.yuaiagent.tool;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.yupi.yuaiagent.constant.FileConstant;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.nio.file.Paths;

public class PDFGenerationTool {

    @Tool(description = "Generate PDF file with given content")
    public String generatePDF(@ToolParam(description = "Name of the file to save the generated PDF") String filename,
                              @ToolParam(description = "Content to be included in the PDF") String content) {
        String fileDir = FileConstant.FILE_SAVE_DIR + "/pdf";
        String filePath = fileDir + "/" + filename;
        try {
            // 创建目录
            FileUtil.mkdir(fileDir);

            // 创建 PdfWriter 和 PdfDocument 对象
            try (PdfWriter writer = new PdfWriter(filePath);
                 PdfDocument pdf = new PdfDocument(writer);
                 Document document = new Document(pdf)) {

                // 使用自定义字体
//                String fontPath = Paths.get("src/main/resources/static/fonts/simsun.ttf").toAbsolutePath().toString();
//                PdfFont font = PdfFontFactory.createFont(fontPath, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);

                // 设置内置中文字体
                PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
                document.setFont(font);

                // 设置文档段落
                Paragraph paragraph = new Paragraph(content);
                // 添加段落并关闭文档
                document.add(paragraph);
            }
            return "PDF generated successfully. File path: " + filePath;
        } catch (Exception e) {
            return "Error occurred while generating PDF. Error message: " + e.getMessage();
        }
    }
}